package com.atguigu.gmall.wms.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.wms.vo.SkuLockVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.wms.mapper.WareSkuMapper;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import com.atguigu.gmall.wms.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuMapper, WareSkuEntity> implements WareSkuService {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private WareSkuMapper wareSkuMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final String LOCK_PREFIX = "stock:lock";
    private static final String KEY_PREFIX = "stock:info";

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<WareSkuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageResultVo(page);
    }

    @Transactional
    @Override
    public List<SkuLockVo> checkLock(List<SkuLockVo> skuLockVos,String orderToken) {
        if (CollectionUtils.isEmpty(skuLockVos)){
            return null;
        }
        //如果不为空遍历 验库存并锁库存 这里封装一个方法
        skuLockVos.forEach(skuLockVo -> {
            checkAndLock(skuLockVo);
        });
        //如果存在锁定失败的库存，需要将所有锁定的成功的库存解锁
        if (skuLockVos.stream().anyMatch(skuLockVo -> !skuLockVo.getLock())){
            skuLockVos.stream().filter(SkuLockVo::getLock).collect(Collectors.toList()).forEach(skuLockVo -> {
                this.wareSkuMapper.unlock(skuLockVo.getWareSkuId(),skuLockVo.getCount());
            });
            // 返回锁定信息
            return skuLockVos;
        }

        // 记录锁定信息到redis中，以方便将来解锁库存 或者 减库存
        this.redisTemplate.opsForValue().set(KEY_PREFIX + orderToken, JSON.toJSONString(skuLockVos));

        // 锁定库存成功，发送消息定时解锁库存
        this.rabbitTemplate.convertAndSend("ORDER_EXCHANGE", "stock.ttl",orderToken);

        // 如果锁定成功，则返回null
        return null;
    }

    private void checkAndLock(SkuLockVo skuLockVo){
        //加分布式锁
        RLock lock = this.redissonClient.getLock(LOCK_PREFIX + skuLockVo.getSkuId());
        lock.lock();

        try {
            //验库存
            List<WareSkuEntity> wareSkuEntities = this.wareSkuMapper.check(skuLockVo.getSkuId(), skuLockVo.getCount());
            if (CollectionUtils.isEmpty(wareSkuEntities)){
                skuLockVo.setLock(false);
                return;
            }
            //锁库存 这里可以通过计算距离的接口判断取哪一个仓库，这里取第一个
            WareSkuEntity wareSkuEntity = wareSkuEntities.get(0);
            if (this.wareSkuMapper.lock(wareSkuEntity.getId(),skuLockVo.getCount()) == 1) {
                skuLockVo.setLock(true);
                skuLockVo.setWareSkuId(wareSkuEntity.getId());
            } else {
                skuLockVo.setLock(false);
            }
        } finally {
            lock.unlock();
        }

    }

}